<?php

namespace app\controller;

use Exception;
use think\facade\Db;
use think\facade\Request;
class Ip
{
    public function get_white()
    {
        $r = Db::table('bound_list')->whereTime('bound_time','>',time()-3600*24*7)->column('ip');
        return response(implode(PHP_EOL,$r))->contentType('text/plain');
    }
    public function  get_black()
    {
        $r = Db::table('black_ip')->where('state',1)->column('ip');
        return response(implode(PHP_EOL,$r))->contentType('text/plain');
    }

    public function  black_add_ip(){
        try {
            $data = Request::param();
            $ip = $data['ip'];
            $operator = $data['operator'];
            $reason = $data["reason"];
            $array = ['ip' => $ip, 'operator' => $operator, 'reason' => $reason,'state'=>'1'];
            $r = Db::table('black_ip')->where('ip', $ip)->find();
            if ($r) {
                if ($r['state'] == '0') {
                    Db::table('black_ip')->where('ip', $ip)->update($array);
                    return (returnjson(msg:'ip ' . $ip . ' 曾于' . date("Y-m-d H:i:s",$r['last_time']) . '被' . $r['operator'] . '解封，封禁成功'));
                }
                return (returnjson(msg: 'ip ' . $ip . ' 曾于' .date("Y-m-d H:i:s",$r['last_time']) . '被' . $r['operator'] . '封禁，不需要再次封禁'));
            }
            Db::table('black_ip')->insert($array);
            return (returnjson(msg: '封禁ip ' . ($ip) . ' 成功'));
        } catch (Exception $e) {
            return returnJson(500, "发生错误", $e->getMessage());
        }
    }
    public function  black_delete_ip()
    {
        try {
            $data = Request::param();
            $ip = $data['ip'];
            $operator = $data['operator'];
            $reason = $data["reason"];
            $array = ['ip' => $ip, 'operator' => $operator, 'reason' => $reason, 'state' => '0'];
            $r = Db::table('black_ip')->where('ip', $ip)->find();
            if (!$r) return (returnjson(201, 'ip ' . ($ip) . ' 不在黑名单中，不需要解封'));
            if ($r['state'] == 0) return (returnjson(msg: 'ip ' . ($ip) . ' 曾于' . date("Y-m-d H:i:s",$r['last_time']) . '被' . ($r['operator']) . '解封,不需要再次解封', data: ['old_data' => $r]));
            Db::table('black_ip')->where('ip', $ip)->update($array);
            return (returnjson(msg: '解封ip ' . ($ip) . ' 成功'));
        } catch (Exception $e) {
            return returnJson(500, "发生错误", $e->getMessage());
        }
    }
}